<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!--  <div>88:{{this.searchForm.code}}</div> -->
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="serviceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item :label="'业务单元：'" v-if="createbtnShow && !useApiGetData">
          <Select filterable clearable v-model="searchForm.code">
            <Option
              @click.native="codeChange(item)"
              v-for="item in this.planLevels"
              :value="item.vsiValue"
              :key="item.key"
              >{{ item.vsiValue }}</Option
            >
          </Select>
        </Form-item>
        <Form-item :label="'业务单元：'" v-if="createbtnShow && useApiGetData">
          <Select filterable clearable v-model="searchForm.code">
            <Option
              @click.native="codeChange(item)"
              v-for="item in this.planLevels"
              :value="item.trgNode"
              :key="item.trgNode"
              >{{ item.trgNode }}</Option
            >
          </Select>
        </Form-item>
        <Form-item :label="'举措大类：'">
          <Select v-model="searchForm.stype" clearable>
            <Option
              @click.native="stypeChange(item)"
              v-for="item in categoryInitiatives"
              :value="item.vsiValue"
              :key="item.vsiValue"
              >{{ item.vsiValue }}</Option
            >
          </Select>
        </Form-item>

        <Form-item :label="'举措细类：'">
          <Select v-model="searchForm.mtype" clearable>
            <Option v-for="item in detailsInitiatives" :value="item.vsiValue" :key="item.vsiValue">{{
              item.vsiValue
            }}</Option>
          </Select>
        </Form-item>
        <Form-item v-if="fromPage == 'creater'" :label="'状态：'">
          <Select v-model="searchForm.wfStatus" clearable>
            <Option v-for="item in processStatusList" :value="item.value" :key="item.value">{{ item.text }}</Option>
          </Select>
        </Form-item>
        <!-- <Form-item v-if="fromPage == 'creater'" :label="'数据范围：'">
          <Select v-model="searchForm.allDataFlag" clearable>
            <Option v-for="item in allDataFlagList" :value="item.value" :key="item.value">{{
              item.text
            }}</Option>
          </Select>
        </Form-item> -->

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" ref="search" @click="searchValueSet()" />
          <RPButton optType="reset" text="高级筛选" @click="advancedSearch()" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="valueSetTable" :config="pageTableConfig" v-if="showTable">
      <div slot="table-bar" v-if="fromPage == 'creater'">
        <RPButton
          v-if="hasPermission('PLAN_TABLE_CREATE')"
          optType="create"
          type="info"
          @click="exportExcel"
          text="下载模板"
        />
        <uploadFile
          :disabled="importDisabled"
          :code="this.searchForm.code"
          :parentCode="this.searchForm.parentCode"
          :url="uploadUrl"
          @uploadSuccess="uploadSuccess"
        ></uploadFile>
        <RPButton optType="create" type="info" text="导出" @click="batchExport" />
        <RPButton
          v-if="hasPermission('PLAN_TABLE_BATCH_EXPORT_NEWEST')"
          optType="create"
          type="info"
          text="导出最新"
          @click="batchExportNewest"
        />
        <RPButton optType="create" type="info" text="删除" @click="batchDel" />
        <RPButton
          v-if="hasPermission('MID-TERM-DELETE')"
          optType="create"
          type="info"
          text="中期删除"
          @click="midtermBatchDel"
        />
        <RPButton :disabled="submitDisabled" optType="create" type="info" text="提交" @click="batchSubmit" />
        <RPButton
          v-if="createbtnShow && hasPermission('PLAN_TABLE_CREATE')"
          :disabled="createDisabled"
          optType="create"
          type="info"
          text="新建"
          @click="goPlanCreatePage"
        />
        <!-- 为了不让最后一个按钮的样式有问题，特别多加一个无意义按钮 -->
        <RPButton optType="create" type="info" text="" style="display:none" />
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { planDataColumns, columnList } from './columns'
import { planLevel, categoryInitiatives } from '@/api/planDataConfig.js'
import uploadFile from './uploadFile'
import planEditAndDetail from './planEditAndDetail.vue'
import midtermEdit from './midtermEdit.vue'
import implementationPlanApi from '../../api/implementationPlanApi'
import coverApi from '../../api/cover'
import sysConfigApi from '@/api/sysConfig.js'
import revisionRecord from '../../components/common/revisionRecord.vue'
import advancedSearch from './advancedSearch.vue'
import { approvalMix } from '@/views/todoCenter/myApproval/approval-mix'
import tableColumnSetting from '@/mixin/tableColumnSetting'
import { PROCESS_STATUS_LIST, PROCESS_STATUS_MAP } from '@/tools/common.js'
import diffrentQuarterConfirm from './diffrentQuarterConfirm'
import { ALL_DATA_FLAG_LIST, ALL_DATA_FLAG_NEW, QUARTER_IS_SAME, QUARTER_IS_NOT_SAME } from './const.js'
import permission from '@/mixin/permission'

export default {
  name: 'planData',
  components: {
    uploadFile
  },
  mixins: [approvalMix, tableColumnSetting, permission],
  props: {
    createbtnShow: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      detault: ''
    },
    parentCode: {
      type: String,
      detault: ''
    },
    uploadUrl: {
      type: String,
      detault: ''
    },
    fromPage: {
      type: String,
      default: 'creater'
    },
    bussinessCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      writePermission: true,
      allDataFlagList: ALL_DATA_FLAG_LIST,
      processStatusList: PROCESS_STATUS_LIST,
      menuNo: this.fromPage == 'creater' ? 'implementation-plan' : 'summary-implementation-plan',
      useApiGetData: true,
      searchForm: {
        stype: '',
        mtype: '',
        code: '',
        wfStatus: '',
        startDate: '',
        startStringDate: '',
        endDate: '',
        endStringDate: '',
        taskdesc: '',
        taskQuarter: '',
        currentStatus: '',
        allDataFlag: ALL_DATA_FLAG_NEW,
        parentCode: this.parentCode,
        fromPage: this.fromPage,
        self: this
      },
      planLevels: [],
      businessUnit: [],
      categoryInitiatives: [],
      detailsInitiatives: [],
      pageTableConfig: {
        loadDataFn: this.getServiceList.bind(this),
        columns: planDataColumns.bind(this)(),
        autoFirst: false, //默认 就是 false, 要配置在这里
        onSelectionChange: this.onSelectionChange,
        pageSize: 100
      },
      columnList: this.fromPage != 'creater' ? this.deleteField(columnList, 'wfStatusName') : columnList,
      ids: []
    }
  },
  computed: {
    createDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    },
    importDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    },
    submitDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    }
  },
  created() {},
  watch: {
    'searchForm.stype': {
      handler(val) {
        if (!val) {
          this.detailsInitiatives = []
          this.searchForm.mtype = ''
        }
      }
    }
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    midtermEdit(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        midtermEdit,
        {
          props: {
            id: row.id || '',
            code: code,
            parentCode: this.parentCode,
            Isedit: true,
            midtermEdit: true,
            dataStatus: Number(row.wfStatus) || 3,
            fromPage: this.fromPage,
            writePermission: this.writePermission
          }
        },
        data => {
          let { pageNum } = this.$refs['valueSetTable'].param
          data && this.searchValueSet(pageNum)
        }
      )
    },
    getConfig() {
      sysConfigApi.getCurrentConfig({ reportName: '数字化转型专项实施方案任务表' }).then(res => {
        const data = res.data.data
        if (data) {
          this.writePermission = data.writePermission === false ? false : true
        }
      })
    },
    init() {
      this.getConfig()
      if (this.useApiGetData) {
        coverApi.getRptReportTrgnodePList({ reportName: '数字化转型专项实施方案任务表' }).then(res => {
          this.planLevels = res.data.data
          if (this.fromPage != 'creater') {
            this.searchForm.code = this.bussinessCode
          }
          // this.searchForm.code = this.planLevels[0].nodeName
          this.$nextTick(() => {
            this.searchValueSet()
          })
        })
        this.categoryInitiatives = []
        categoryInitiatives.map(item => {
          if (item.vsiValue !== '总体任务' && item.vsiValue !== '重点行业数字化转型') {
            this.categoryInitiatives.push(item)
          }
        })
        // this.categoryInitiatives = categoryInitiatives
        this.searchForm.stype = ''
      } else {
        this.planLevels = planLevel
        if (this.createbtnShow) {
          // this.searchForm.code = this.planLevels[0].vsiValue
          // this.categoryInitiatives = this.planLevels[0].children
          this.searchForm.stype = ''
        } else {
          if (this.bussinessCode) {
            this.searchForm.code = this.bussinessCode
            this.categoryInitiatives = this.planLevels.find(item => item.vsiValue == this.bussinessCode)
              ? this.planLevels.find(item => item.vsiValue == this.bussinessCode).children
              : []
            this.detailsInitiatives = []
          }
        }
        this.searchValueSet()
      }
    },
    url(type, pathname) {
      return window.RPConfig[type] + pathname
    },
    revisionRecord(row) {
      new this.$pageModal(revisionRecord, {
        props: {
          taskCode: row.taskCode,
          logType: this.fromPage == 'Summary' ? 1 : 5
        }
      })
    },
    exportFun(row) {
      // 导出
      coverApi.downLoadFun({
        url: this.url('itShare', `/wfRptPlantask/listExport?id=${row.id}&trg_node&stype&mtype&task_code`)
      })
    },
    deleteFun(params) {
      let idList = []
      if (Array.isArray(params)) {
        idList = [...params]
      } else if (params.id) {
        idList.push(params.id)
      }
      this.$confirm({
        title: '提交',
        content: '是否删除该实施方案任务表？'
      }).then(() => {
        coverApi
          .coverDeleteData({
            type: this.fromPage,
            data: idList
          })
          .then(result => {
            if (result.data.code == 200) {
              this.$Message.success({
                content: '删除成功',
                duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
              })
            }
            this.searchValueSet()
          })
      })
    },
    midterDeleteFun(params) {
      let idList = []
      if (Array.isArray(params)) {
        idList = [...params]
      } else if (params.id) {
        idList.push(params.id)
      }
      this.$confirm({
        title: '提交',
        content: '是否删除该实施方案任务表？'
      }).then(() => {
        coverApi
          .coverDeleteMidtermData({
            type: this.fromPage,
            data: idList
          })
          .then(result => {
            if (result.data.code == 200) {
              this.$Message.success({
                content: '删除成功',
                duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
              })
            }
            this.searchValueSet()
          })
      })
    },
    uploadSuccess(data) {
      if (data.code == QUARTER_IS_SAME) {
        this.searchValueSet()
      } else if (data.code == QUARTER_IS_NOT_SAME) {
        this.diffrentQuarterConfirm(data)
      }
    },
    diffrentQuarterConfirm(data) {
      new this.$pageModal(
        diffrentQuarterConfirm,
        {
          props: {
            fromAction: 'import',
            data
          }
        },
        data => {
          if (data) {
            let actionSource = data.actionSource
            let msg = ''
            if (actionSource == 'NotModifyAndSubmit') {
              msg = '导入成功'
              //  "excel导入方式 0-保持并提交 1-修改并提交"
              data.optType = '0'
            } else if (actionSource == 'ModifyAndSubmit') {
              msg = '修改季度导入成功'
              //  "excel导入方式 0-保持并提交 1-修改并提交"
              data.optType = '1'
            }
            this.confirmUpload(data, msg)
          }
        }
      )
    },
    confirmUpload(data, msg) {
      // this.disabledAction = true
      coverApi
        .confirmUpload({
          cacheDataId: data.cacheDataId,
          optType: data.optType
        })
        .then(res => {
          if (res.data.code == 200) {
            this.$Message.success({
              content: msg,
              duration: 3
            })
            this.searchValueSet()
          } else {
            this.$Message.error({
              content: res.data.msg || '操作失败',
              duration: 3
            })
          }
          this.$emit('Close', true)
        })
        .finally(() => {
          // this.disabledAction = false
        })
    },
    codeChange(list) {
      if (!this.useApiGetData) {
        this.categoryInitiatives = list.children
        this.searchForm.stype = ''
        this.detailsInitiatives = []
        this.searchForm.mtype = ''
      }
    },
    stypeChange(list) {
      this.detailsInitiatives = list.children
      this.searchForm.mtype = ''
    },
    //获取举措大类列表
    getCategoryInitiatives() {
      implementationPlanApi.getCategoryInitiatives().then(res => {
        this.categoryInitiatives = res.data
      })
    },
    //获取举措细类列表
    getDetailsInitiatives() {
      implementationPlanApi.getDetailsInitiatives().then(res => {
        this.detailsInitiatives = res.data
      })
    },
    // 下载文件 TODO: 改下载链接是否需要走网关代理需要验证
    exportExcel() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = this.url('itShare', '/wfRptPlantask/excelExport')
      link.setAttribute('download', 'fillname')
      document.body.appendChild(link)
      link.click()
      link.remove()
    },
    goDetail(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        planEditAndDetail,
        {
          props: {
            id: row.id || '',
            disabledPage: true,
            code: code,
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            dataStatus: Number(row.wfStatus) || 3
          }
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },

    goUpdateProgress(row) {
      let params = {
        taskCode: row.taskCode,
        trgNode: row.trgNode,
        stype: '',
        mtype: '',
        currentPage: 1, //当前页码
        pageSize: 100, //每页条数
        sortOrderBy: 'DESC',
        sortPropName: 'create_time'
      }
      coverApi
        .getCoverTableList({
          data: params,
          type: this.fromPage
        })
        .then(res => {
          let { records } = res.data.data
          if (Array.isArray(records) && records.length == 1) {
            this.goPlanCreatePage(records)
          } else {
            let content = '您选中的数据可能已经被删除，请刷新页面再次确认'
            if (records.length > 0) {
              content = '根据编码查询您选中的数据有重复，请先处理数据问题'
            }
            this.$Message.error({
              content,
              duration: 3
            })
          }
        })
    },

    goEdit(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        planEditAndDetail,
        {
          props: {
            id: row.id || '',
            code: code,
            parentCode: this.parentCode,
            Isedit: true,
            dataStatus: Number(row.wfStatus) || 3,
            fromPage: this.fromPage,
            writePermission: this.writePermission
          }
        },
        data => {
          let { pageNum } = this.$refs['valueSetTable'].param
          data && this.searchValueSet(pageNum)
        }
      )
    },
    goPlanCreatePage(associationData) {
      if (!Array.isArray(associationData)) {
        associationData = []
      }
      new this.$sidelipPage(
        planEditAndDetail,
        {
          props: {
            code: '',
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            associationData,
            fromAction: 'updateProgress'
          }
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },

    getServiceList: tableObj => {
      let { responseProcess, param } = tableObj
      let {
        pageNum,
        pageSize,
        code,
        stype,
        mtype,
        wfStatus,
        allDataFlag,
        taskdesc,
        startDate,
        startStringDate,
        endDate,
        endStringDate,
        taskQuarter,
        currentStatus,
        self
      } = param
      let params = {
        trgNode: code,
        stype: stype,
        mtype: mtype,
        wfStatus: wfStatus,
        allDataFlag: allDataFlag,
        startDate: startDate,
        startStringDate: startStringDate,
        endDate: endDate,
        endStringDate: endStringDate,
        taskdesc: taskdesc,
        taskQuarter: taskQuarter,
        currentStatus: currentStatus,
        currentPage: pageNum, //当前页码
        pageSize: pageSize //每页条数
        //  sortOrderBy: 'DESC',
        //  sortPropName: 'create_time'
      }
      coverApi
        .getCoverTableList({
          type: param.fromPage,
          data: params
        })
        .then(res => {
          if (res.data.code == 200) {
            let { current, pages, size, total, records } = res.data.data
            if (records && records.length) {
              records.forEach(element => {
                element.wfStatusName = PROCESS_STATUS_MAP[element.wfStatus]
              })
            }
            responseProcess({
              pageNum: Number(current),
              pageSize: Number(size),
              pages: Number(pages),
              records: records || [],
              total: Number(total)
            })
          } else {
            self.$Message.error({
              content: res.data.msg || '操作失败',
              duration: 3
            })
          }
          self.ids = []
        })
    },
    //搜索
    searchValueSet(pageNum = null) {
      this.$refs['valueSetTable'].load(this.searchForm, pageNum)
    },
    advancedSearch() {
      new this.$pageModal(
        advancedSearch,
        {
          props: {
            advanceSearchForm: this.searchForm,
            planLevels: this.planLevels,
            categoryInitiatives: this.categoryInitiatives,
            detailsInitiatives: this.detailsInitiatives,
            processStatusList: this.processStatusList,
            useApiGetData: this.useApiGetData,
            createbtnShow: this.createbtnShow,
            allDataFlagList: this.allDataFlagList,
            fromPage: this.fromPage
          }
        },
        data => {
          if (data) {
            this.searchForm = data
            let category = this.categoryInitiatives.find(item => item.vsiValue == this.searchForm.stype)
            if (category) {
              this.detailsInitiatives = category.children
            }
            this.searchValueSet()
          }
        }
      )
    },
    _batchCommit(params) {
      coverApi.commitwfRptDgcalHrhx(params).then(result => {
        if (result.data.code == 200) {
          this.$Message.success({
            content: '提交成功',
            duration: 3
          })
        } else {
          this.$Message.error({
            content: result.data.msg || '提交失败',
            duration: 3
          })
        }
        this.searchValueSet()
      })
    },
    // 批量提交
    commitFun(selectedData) {
      this.$confirm({
        title: '提交',
        content: '是否要批量提交?'
      }).then(() => {
        sysConfigApi.getCurrentConfig({ reportName: '数字化转型专项实施方案任务表' }).then(res => {
          const data = res.data.data
          if (data) {
            // 判断填报配置季度是否相同
            let configQuarter = (data.taskSubmitYear || '') + '-' + (data.taskSubmitQuarter || '')
            let diffrentQuarterFlag = false
            let params = {
              idList: selectedData.map(item => item.id)
            }
            selectedData.forEach(item => {
              if (item.taskQuarter != configQuarter && configQuarter && item.taskQuarter) {
                diffrentQuarterFlag = true
              }
            })

            if (diffrentQuarterFlag) {
              new this.$pageModal(
                diffrentQuarterConfirm,
                {
                  props: {
                    fromAction: 'batchSubmit',
                    data: {},
                    configQuarter
                  }
                },
                data => {
                  if (data) {
                    let actionSource = data.actionSource
                    if (actionSource == 'NotModifyAndSubmit') {
                      this._batchCommit(params)
                    } else if (actionSource == 'ModifyAndSubmit') {
                      params.taskQuarter = configQuarter
                      this._batchCommit(params)
                    }
                  }
                }
              )
            } else {
              this._batchCommit(params)
            }
          }
        })
      })
    },
    onSelectionChange(selection) {
      this.ids = []
      selection.forEach(element => {
        // console.log(element)
        this.ids.push({
          id: element.id,
          wfStatus: element.wfStatus,
          planName: element.planName,
          taskQuarter: element.taskQuarter
        })
      })
    },
    getUrl(type, pathname) {
      return window.RPConfig[type] + pathname
    },
    // 导出
    listExport(ids) {
      this.$confirm({
        title: '导出',
        content: '是否要批量导出?'
      }).then(() => {
        const url = window.origin + '/' + this.getUrl('itShare', `/wfRptPlantask/listExport`)
        coverApi.downloadFile2(url, ids)
      })
    },
    // 批量导出
    batchExport() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        ids.push(item.id)
      })
      this.listExport(ids)
    },
    // 批量导出最新数据
    batchExportNewest() {
      this.$confirm({
        title: '导出',
        content: '是否要导出最新数据?'
      }).then(() => {
        const url = window.origin + '/' + this.getUrl('itShare', `/wfRptPlantask/listExport/last`)
        coverApi.downloadFile2(url)
      })
    },
    // 批量删除
    batchDel() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        // 状态为1(待提交)时可以删除
        if (item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          ids.push(item.id)
        }
      })
      if (ids.length > 0) {
        this.deleteFun(ids)
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以删除，请重试',
          duration: 3
        })
      }
    },
    // 中期批量删除
    midtermBatchDel() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        ids.push(item.id)
      })
      this.midterDeleteFun(ids)
    },
    // 批量提交
    batchSubmit() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const selectedData = []
      this.ids.forEach(item => {
        // 状态为1提交
        if (item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          selectedData.push(item)
        }
      })
      if (selectedData.length > 0) {
        this.commitFun(selectedData)
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以提交，请重试',
          duration: 3
        })
      }
    }
  },
  directives: {}
}
</script>
<style lang="less" scoped>
/deep/.table-bar button:last-child {
  color: #ffffff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
}

/deep/ .handle-cus {
  font-size: 18px;
  &:hover {
    color: #ff6f4b;
    cursor: pointer;
  }
}
</style>
